<?php
namespace app\shop\controller\callback;

use app\common\model\shop\ozon\OzonGoodsModel;
use app\common\model\shop\ozon\OzonGoodsPushMsgModel;
use app\common\model\shop\ozon\OzonGoodsSkuModel;
use app\common\model\shop\ShopsModel;
use app\common\service\shop\Ozon;
use think\admin\Controller;
use think\facade\Db;
use think\facade\Log;

/**
 * Ozone回调通知
 * @package app\shop\controller\callback
 * @author shirukun
 * @DateTime 2024/12/12 10:02
 */
class Ozone extends Controller
{
    /**
     * 接收推送通知
     * @author shirukun
     * @return void
     */
    public function notice()
    {
        $param = $this->request->param();

        Log::record("Ozone通知: " . json_encode($param,320) . "--------------------------------\n");

        empty($param['message_type']) && $this->error('非法请求！');

        switch ($param['message_type']){
            case 'TYPE_PING': // 检查连接

                Log::record("Ozone通知[检查连接]: " . json_encode($param,320) . "\n");
                return json_encode([
                    "version" => "1.o",
                    "name" => "跨境电商运营系统",
                    "time" => "2019-08-24T14:15:22Z"
                ],320);

            case 'TYPE_CREATE_OR_UPDATE_ITEM':
                Log::record("Ozone通知[商品创建更新]: " . json_encode($param,320) . "\n");
                try {
                    $this->type_create_or_update($param);
                    return json_encode(["result" => true],320);
                }catch (\Exception $e){

                    Log::error("Ozone通知[异常捕获]: " . $e->getMessage() . "\n");
                    return json_encode(["error" => [
                        "code" => "ERROR_UNKNOWN ",
                        "message" => "系统错误",
                        "details" => $e->getMessage(),
                    ]],320);
                }
            default:
                $this->error('未知的通知！');
                break;
        }

    }

    // 商品创建和更新，或在此过程中发生的错误或通过
    private function type_create_or_update($param)
    {
//        {
//            "message_type": "TYPE_CREATE_OR_UPDATE_ITEM",
//            "seller_id": 2343274,
//            "offer_id": "1619330924-oasb",
//            "product_id": 1291236629,
//            "is_error": true,
//            "changed_at": "1970-01-01T00:00:00Z"
//        }

        $goods_sku_info = OzonGoodsSkuModel::mk()->where(['goods_nu' => $param['offer_id']])->find();
        //        halt($goods_sku_info);
        if(empty($goods_sku_info)){
            throw new \Exception("系统商品sku不存在");
        }

        try {
            // 启动事务
            Db::startTrans();

            // 1、更改状态----------------------------------------------------------------------------------------------------------------
            if ($param['is_error']) { // 有错误

                // 更改sku表状态
                OzonGoodsSkuModel::mk()->update(['push_status' => 3, 'product_id'=>$param['product_id']], ['id' => $goods_sku_info['id']]);
                // 更改spu表状态
                OzonGoodsModel::mk()->update(['push_status' => 3], ['id' => $goods_sku_info['goods_id']]);

            } else { // 无错误

                // 更改sku表状态
                OzonGoodsSkuModel::mk()->update(['push_status' => 2, 'product_id'=>$param['product_id']], ['id' => $goods_sku_info['id']]);

                // 检查是否全部成功
                $goods_sku_success_no = OzonGoodsSkuModel::mk()->where([['goods_id', '=', $goods_sku_info['goods_id']], ['push_status', '<>', 2]])->find();
                if (empty($goods_sku_success_no)) { // 不存在非成功的
                    // 更改spu表状态 (成功)
                    OzonGoodsModel::mk()->update(['push_status' => 2], ['id' => $goods_sku_info['goods_id']]);
                }
            }

            // 2、获取错误信息
            // 如果检测到同一批次的数据最后一个处理完成则获取错误信息---------------------------------------------------------------------------------------------

            // 检查一批(同一task_id)所有sku推送状态
            $goods_sku_push_status = OzonGoodsSkuModel::mk()->where([['task_id', '=', $goods_sku_info['task_id']]])->column('push_status');
//            halt($goods_sku_push_status);
            if(!in_array(1,$goods_sku_push_status)){ // 已全部处理
//                Log::info("批次号：【" . $goods_sku_info['task_id'] . "】已全部处理-------------------------------------------------\n");
                // 获取店铺配置
                $shop_id = OzonGoodsModel::mk()->where(['id' => $goods_sku_info['goods_id']])->value('shop_id');
                $shop = ShopsModel::mk()->find($shop_id);
                // 获取一个批次的错误信息
                $OzonClient = new Ozon([
                    // 测试订单账号
                    'client_id' => $shop['client_id'],
                    'api_key' => $shop['api_key'],
                ]);
                $res = $OzonClient->getGoodsImportMsg($goods_sku_info['task_id']);

//                Log::info("获取错误信息：   " . json_encode($res) . "\n");
                if($res['code'] == 0){ // 获取失败
                    // 记录错误
                    OzonGoodsPushMsgModel::mk()->insert([
                        'type' => 1,
                        'task_id' => $goods_sku_info['task_id'],
                        'message' => $OzonClient->getErr(),
                        'description' => '获取商品创建或更新结果信息失败,批次号为：' . $goods_sku_info['task_id'],
                    ]);
                }else{ // 获取成功
                    $res_items = $res['data']['result']['items'];
                    $data = [];
                    foreach ($res_items as $k => $v){
                        foreach ($v['errors'] as $kk => $vv){
                            $data[] = [
                                'type' => 1,
                                'task_id' => $goods_sku_info['task_id'],
                                'offer_id' => $v['offer_id'],
                                'attribute_id' => $vv['attribute_id'],
                                'level' => $vv['level'],
                                'message' => $vv['message'],
                                'description' => $vv['description'],
                            ];
                        }
                    }
                    // 记录错误
                    OzonGoodsPushMsgModel::mk()->insertAll($data);
                }

            }

            // 提交事务
            Db::commit();
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

        if(empty($goods_sku_info['ozon_sku'])){
            sysqueue('更新商品:'.$param['offer_id'].'ozonsku', 'ozonAttribute bindSku '.$param['offer_id']);
        }

    }


}